import 'dart:io';
import 'package:excel/excel.dart';

void main() async {
  await convertXlsxToMarkdown('../indicator_api.xlsx'); //../
}

Future<void> convertXlsxToMarkdown(String xlsxPath) async {
  var bytes = File(xlsxPath).readAsBytesSync();
  var excel = Excel.decodeBytes(bytes);

  StringBuffer allMarkdownBuffer = StringBuffer(); // 汇总 Markdown

  for (var table in excel.tables.keys) {
    var sheet = excel.tables[table];
    if (sheet == null || sheet.rows.isEmpty) continue;

    String sanitizedTableName = sanitizeFileName(table); // 清理文件名
    StringBuffer markdownBuffer = StringBuffer();

    allMarkdownBuffer.writeln('## $table\n'); // 在汇总文件中添加表格标题

    for (var row in sheet.rows) {
      if (row.length < 3) continue; // 确保至少有三列

      String title = row[0]?.value.toString() ?? ""; // 第一列
      String description = row[1]?.value.toString() ?? ""; // 第二列
      String content = row[2]?.value.toString() ?? ""; // 第三列

      if (title.isNotEmpty && description.isNotEmpty && content.isNotEmpty) {
        String section = "### $title $description\n```c\n$content\n```\n---\n";
        //markdownBuffer.writeln("\n");

        markdownBuffer.writeln(section); // 添加到单独的 Markdown 文件
        allMarkdownBuffer.writeln(section); // 添加到汇总 Markdown 文件
      }
    }

    if (markdownBuffer.isNotEmpty) {
      String markdownPath =
          await saveMarkdown(sanitizedTableName, markdownBuffer.toString());
      print('Markdown 文件已生成: $markdownPath');
    }
  }

  // 保存汇总 Markdown 文件
  if (allMarkdownBuffer.isNotEmpty) {
    String summaryPath =
        await saveMarkdown("函数汇总", allMarkdownBuffer.toString());
    print('Markdown 汇总文件已生成: $summaryPath');
  }
}

// **清理文件名，移除特殊字符**
String sanitizeFileName(String name) {
  return name.replaceAll(RegExp(r'[\/:*?"<>|]'), '_'); // 替换非法字符为 '_'
}

// **保存 Markdown 文件**
Future<String> saveMarkdown(String fileName, String content) async {
  String filePath = '$fileName.md';
  File file = File(filePath);
  await file.writeAsString(content);
  return filePath;
}
